<template>
	<div>
		<Breadcrumb :opt-data="breadcrumbOptData"></Breadcrumb>
		<PageLayout>
			<div class="table-container height-100">
				<EZTable
					v-loading="tableLoading"
					:table-id="tableId"
					:table-hdl="tableHdl"
					:rows="platformData"
					:custom-empty="true"
					@pageChanged="getPlatformData"
					@sizeChanged="getPlatformData"
					@filterChange="getPlatformData">
					<EmptyContent slot="empty" :opt-data="tableOptData"></EmptyContent>
				</EZTable>
			</div>
			<el-dialog
				:title="`${!isEditPlatform ? '新增' : '编辑'}第三方平台`"
				:visible.sync="showPlatformDialog"
        :close-on-click-modal="false"
				width="750px"
				center>
				<el-form
					v-loading="platformFormLoading"
					:ref="platformFormRef"
					:model="platformForm"
					:rules="platformFormRules"
					size="small"
					label-width="95px">
					<el-form-item label="平台名称" prop="name">
						<el-input v-model="platformForm.name" placeholder="请填写第三方平台名称"></el-input>
					</el-form-item>
					<el-form-item label="属性映射">
						<el-tabs value="base" type="border-card">
							<el-tab-pane
								v-for="mapData in basePropMapData" :key="mapData.type"
								:label="mapData.title" :name="mapData.type">
								<el-form-item
									v-for="config in mapData.configs" :key="config.key"
									:label="config.label" :prop="`basePropMap.${config.key}`">
									<el-row>
										<el-col :span="8">
											<el-input :value="config.key"></el-input>
										</el-col>
										<el-col :span="2" class="text-align-center pad-lft-rgt-5">=></el-col>
										<el-col :span="14">
											<el-input
												v-model="platformForm.basePropMap[config.key]"
												:placeholder="`请填写${config.label}映射`"></el-input>
										</el-col>
									</el-row>
								</el-form-item>
							</el-tab-pane>
						</el-tabs>
					</el-form-item>
					<el-form-item label="备注">
						<el-input type="textarea" v-model="platformForm.remarks" placeholder="请填写备注"></el-input>
					</el-form-item>
					<div class="text-align-right">
						<el-form-item>
							<el-button size="medium" @click="showPlatformDialog = false">取消</el-button>
							<el-button size="medium" type="primary" @click="platformFormSubmit">提交</el-button>
						</el-form-item>
					</div>
				</el-form>
			</el-dialog>
		</PageLayout>
	</div>
</template>

<script>
	// product_id   // 产品ID
	// device_ESN   // 设备序列号
	// client_id    // 设备ID
	// device_name  // 设备名称
	// deviceAlias
	// positionCode  // 位置编码
	//
	// ip     // IP地址
	// mac    // MAC地址
	// ssid  // SSID
	// rssi  // 信号强度值
	//
	// vendor    // 设备制造商
	// model   // 设备型号
	// hardwareVersion  // 硬件版本
	// softwareVersion  // 软件版本
	// protocolVersion  // 协议版本
	//
	// last_connection_time   // 最近上线时间
	// lastConnectionTime  // 最近上线时间
	// currentTime  // 当前时间
	// systemStartTime // 系统启动时间
	//
	// report_interval  // 上报间隔
	// iotUrl  // IoT服务URL
	// ntpServer  // NTP服务器
	// autoRebootTime  // 自动重启时间
	// sleepTime  // 设备休眠时间
	//
	// upgradeProgress   // 升级进度
	// lastUpgradeOkTime // 最近升级成功时间
	// lastUpgradeFailTime  // 最近升级失败时间
	// lastUpgradeErrMsg  // 最近升级错误信息

	import EZTable from '@/components/table/EZTable.vue';
	import tableConfig from "@/config/table/thirdPartyPlatform";
	import {tableIdConfig, tableOptBtnConfig} from "@/config/table";
	import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
	import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
	import {commonConfig, momentFormat} from "@/config/common";
	import {secretHdl} from "@/modules/secretHdl";
	import {msgCode} from "@/config/string";
	import {routerMeta} from "@/router/routerMeta";

	const FileSaver = require('file-saver');

	export default {
		name: "ThirdPartyPlatform",
		components: {
			EZTable
		},
		data() {
			return {
				commonConfig: commonConfig,
				tableLoading: true,
				tableId: tableIdConfig.thirdPartyPlatform,
				tableHdl: null,
				platformData: [],
				showPlatformDialog: false,
				platformFormLoading: false,
				platformFormRef: 'platformFormRef',
				platformForm: {
					name: '',
					basePropMap: {
						product_id: '',
						device_ESN: '',
						client_id: '',
						device_name: '',
						deviceAlias: '',
						positionCode: '',
						ip: '',
						mac: '',
						ssid: '',
						rssi: '',
						vendor: '',
						model: '',
						hardwareVersion: '',
						softwareVersion: '',
						protocolVersion: '',
						lastConnectionTime: '',
						currentTime: '',
						systemStartTime: '',
						report_interval: '',
						iotUrl: '',
						ntpServer: '',
						autoRebootTime: '',
						sleepTime: '',
						upgradeProgress: '',
						lastUpgradeOkTime: '',
						lastUpgradeFailTime: '',
						lastUpgradeErrMsg: '',
					},
					remarks: '',
				},
				platformFormRules: {},
				basePropMapData: [
					{
						type: 'base',
						title: '基础',
						configs: [
							{
								key: 'product_id',
								label: '产品ID'
							},
							{
								key: 'device_ESN',
								label: '设备序列号'
							},
							{
								key: 'client_id',
								label: '设备ID'
							},
							{
								key: 'device_name',
								label: '设备名称'
							},
							{
								key: 'deviceAlias',
								label: '设备类别'
							},
							{
								key: 'positionCode',
								label: '位置编码'
							},
						]
					},
					{
						type: 'network',
						title: '网络',
						configs: [
							{
								key: 'ip',
								label: 'IP地址'
							},
							{
								key: 'mac',
								label: 'MAC地址'
							},
							{
								key: 'ssid',
								label: 'SSID'
							},
							{
								key: 'rssi',
								label: '信号强度值'
							},
						]
					},
					{
						type: 'information',
						title: '信息',
						configs: [
							{
								key: 'vendor',
								label: '设备制造商'
							},
							{
								key: 'model',
								label: '设备型号'
							},
							{
								key: 'hardwareVersion',
								label: '硬件版本'
							},
							{
								key: 'softwareVersion',
								label: '软件版本'
							},
							{
								key: 'protocolVersion',
								label: '协议版本'
							},
						]
					},
					{
						type: 'status',
						title: '状态',
						configs: [
							{
								key: 'lastConnectionTime',
								label: '最近上线时间'
							},
							{
								key: 'currentTime',
								label: '当前时间'
							},
							{
								key: 'systemStartTime',
								label: '系统启动时间'
							},
						]
					},
					{
						type: 'config',
						title: '配置',
						configs: [
							{
								key: 'report_interval',
								label: '上报间隔'
							},
							{
								key: 'iotUrl',
								label: 'IoT服务URL'
							},
							{
								key: 'ntpServer',
								label: 'NTP服务器'
							},
							{
								key: 'autoRebootTime',
								label: '自动重启时间'
							},
							{
								key: 'sleepTime',
								label: '设备休眠时间'
							},
						]
					},
					{
						type: 'upgrade',
						title: '升级',
						configs: [
							{
								key: 'upgradeProgress',
								label: '升级进度'
							},
							{
								key: 'lastUpgradeOkTime',
								label: '升级成功时间'
							},
							{
								key: 'lastUpgradeFailTime',
								label: '升级失败时间'
							},
							{
								key: 'lastUpgradeErrMsg',
								label: '升级错误信息'
							},
						]
					},
				],
				isEditPlatform: false
			};
		},
		computed: {
			breadcrumbOptData() {
				return [
					{
						type: 'btn',
						label: '导出至分控',
						icon: 'icon-zujiantubiao-daochu',
						callback: () => {
							this.exportToControl();
						}
					},
					{
						type: 'btn',
						label: '新增平台配置',
						icon: 'icon-tianjia',
						callback: () => {
							this.platformAdd();
						}
					},
				];
			},
			tableOptData() {
				return [
					{
						type: 'btn',
						label: '新增平台配置',
						icon: 'icon-tianjia',
						callback: () => {
							this.platformAdd();
						}
					}
				];
			},
		},
		activated() {
			this.initTableConfig();
			this.initPlatformForm();
			this.initPlatformFormRules();
			this.getPlatformData();
		},
		methods: {
			initTableConfig() {
				if (this.tableHdl) return;
				const {columns = [], filters = []} = getTableConfig(this.tableId, tableConfig);
				assembleTableOptBtn(columns, ({type = '', data = {}}) => {
					if (!type) return;
					const platform = deepCopyWithJson(data);
					switch (type) {
						case tableOptBtnConfig.edit.type:
							this.showPlatformDialog = true;
							this.isEditPlatform = true;
							const {_id = '', name = '', basePropMap = {}, remarks = ''} = platform;
							const {
								product_id = 'product_id',
								device_ESN = 'device_ESN',
								client_id = 'client_id',
								device_name = 'device_name',
								deviceAlias = 'deviceAlias',
								positionCode = 'positionCode',
								ip = 'ip',
								mac = 'mac',
								ssid = 'ssid',
								rssi = 'rssi',
								vendor = 'vendor',
								model = 'model',
								hardwareVersion = 'hardwareVersion',
								softwareVersion = 'softwareVersion',
								protocolVersion = 'protocolVersion',
								lastConnectionTime = 'lastConnectionTime',
								currentTime = 'currentTime',
								systemStartTime = 'systemStartTime',
								report_interval = 'report_interval',
								iotUrl = 'iotUrl',
								ntpServer = 'ntpServer',
								autoRebootTime = 'autoRebootTime',
								sleepTime = 'sleepTime',
								upgradeProgress = 'upgradeProgress',
								lastUpgradeOkTime = 'lastUpgradeOkTime',
								lastUpgradeFailTime = 'lastUpgradeFailTime',
								lastUpgradeErrMsg = 'lastUpgradeErrMsg',
							} = basePropMap;
							this.platformForm = {
								_id: _id,
								name: name,
								basePropMap: {
									product_id, device_ESN, client_id, device_name, deviceAlias,
									positionCode, ip, mac, ssid, rssi, vendor, model,
									hardwareVersion, softwareVersion, protocolVersion, lastConnectionTime,
									currentTime, systemStartTime, report_interval, iotUrl, ntpServer,
									autoRebootTime, sleepTime, upgradeProgress, lastUpgradeOkTime,
									lastUpgradeFailTime, lastUpgradeErrMsg
								},
								remarks: remarks
							};
							break;
						case tableOptBtnConfig.delete.type:
							this.platformDelete(platform);
							break;
						case tableOptBtnConfig.export.type:
							this.exportToControl();
							break;
						case 'mapRuleConfig':
							this.$router.push({
								name: routerMeta.platformInterface.name,
								params: {pid: platform._id}
							});
							break;
						default:
							break;
					}
				});
				this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
			},
			initPlatformForm() {
				this.platformForm = {
					name: '',
					basePropMap: {
						product_id: 'product_id',
						device_ESN: 'device_ESN',
						client_id: 'client_id',
						device_name: 'device_name',
						deviceAlias: 'deviceAlias',
						positionCode: 'positionCode',
						ip: 'ip',
						mac: 'mac',
						ssid: 'ssid',
						rssi: 'rssi',
						vendor: 'vendor',
						model: 'model',
						hardwareVersion: 'hardwareVersion',
						softwareVersion: 'softwareVersion',
						protocolVersion: 'protocolVersion',
						lastConnectionTime: 'lastConnectionTime',
						currentTime: 'currentTime',
						systemStartTime: 'systemStartTime',
						report_interval: 'report_interval',
						iotUrl: 'iotUrl',
						ntpServer: 'ntpServer',
						autoRebootTime: 'autoRebootTime',
						sleepTime: 'sleepTime',
						upgradeProgress: 'upgradeProgress',
						lastUpgradeOkTime: 'lastUpgradeOkTime',
						lastUpgradeFailTime: 'lastUpgradeFailTime',
						lastUpgradeErrMsg: 'lastUpgradeErrMsg',
					},
					remarks: '',
				};
			},
			initPlatformFormRules() {
				this.platformFormRules = {
					name: [
						{required: true, message: '请填写第三方平台名称', trigger: 'blur'}
					],
				};
				this.basePropMapData.forEach(mapData => {
					const {configs = []} = mapData;
					configs.forEach(config => {
						const {key = '', label = ''} = config;
						this.platformFormRules[key] = [
							{required: true, message: `请填写${label}映射`, trigger: 'blur'}
						]
					});
				});
			},
			resetPlatformForm() {
				this.initPlatformForm();
				const platformForm = this.$refs[this.platformFormRef];
				platformForm && platformForm.resetFields();
			},
			getPlatformData() {
				this.tableLoading = true;
				const selector = {};
				const tableParam = this.tableHdl.assembleTableParam();
				API.thirdPartyPlatform.thirdPartyPlatformList({...tableParam, selector}).then(result => {
					this.tableLoading = false;
					const {data = [], total = 0} = result;
					this.platformData = data;
					this.tableHdl.total = total;
				}).catch(err => {
					this.tableLoading = false;
				});
			},
			platformAdd() {
				this.isEditPlatform && this.resetPlatformForm();
				this.showPlatformDialog = true;
				this.isEditPlatform = false;
			},
			platformDelete(platform = {}) {
				confirmHandle({label: `确定要删除第三方平台：${platform.name} 吗?`}).then(() => {
					API.thirdPartyPlatform.thirdPartyPlatformDelete({_id: platform._id}).then(result => {
						messageHandle({code: msgCode.DELETE_SUCCESS, title: '第三方平台'});
						this.tableHdl.judgeTableMatched();
						this.getPlatformData();
						this.resetPlatformForm();
					});
				}).catch(() => {
				});
			},
			platformFormSubmit() {
				this.$refs[this.platformFormRef].validate((valid) => {
					if (!valid) return;
					this.platformFormLoading = true;
					if (!this.isEditPlatform) {
						API.thirdPartyPlatform.thirdPartyPlatformAdd({...this.platformForm}).then(result => {
							messageHandle({code: msgCode.ADD_SUCCESS, title: '第三方平台'});
							this.showPlatformDialog = false;
							this.platformFormLoading = false;
							this.getPlatformData();
							this.resetPlatformForm();
						}).catch(err => {
							console.log('err', err)
							this.platformFormLoading = false;
						});
					} else {
						API.thirdPartyPlatform.thirdPartyPlatformEdit({...this.platformForm}).then(result => {
							messageHandle({code: msgCode.EDIT_SUCCESS, title: '第三方平台'});
							this.showPlatformDialog = false;
							this.platformFormLoading = false;
							this.getPlatformData();
							this.resetPlatformForm();
						}).catch(err => {
							console.log('err', err)
							this.platformFormLoading = false;
						});
					}
				});
			},
			exportToControl() {
				confirmHandle({label: `是否确定要导出第三方平台对接数据至分控 ？`}).then(() => {
					this.tableLoading = true;
					API.thirdPartyPlatform.thirdPartyPlatformExport().then(result => {
						console.log('##### result #####', result);
						const ts = moment().format(momentFormat.dateTimeDetailFlat);
						const rand = Math.random() * 16;
						const payload = secretHdl.encrypt(JSON.stringify(result.data), `${ts}${rand}`);
						const interfaces = `<<<\nezControl\nV1.0.0\n${ts}\n${rand}\n${payload.length}\n${payload}\n>>>`;
						FileSaver.saveAs(new Blob([interfaces]), "第三方平台对接.cfg");
						this.tableLoading = false;
					}).catch(err => {
						this.tableLoading = false;
						console.log('err', err)
					});
				}).catch((err) => {
					console.log('##### err #####', err);
				});
			}
		},
	}
</script>

<style scoped lang="less">

</style>
